import {
	confirmCconfig,
	socketNowIP
} from "@/utils/config"
import router from '@/router'
import {
	Message,
	MessageBox
} from 'element-ui'
import socket from "@/socket";
import {
	getToken,
	removeToken
} from '@/utils/auth'



const socketService = {
	state: () => ({
		socket: {
			onopen: () => {},
			onerror: () => {},
			onmessage: () => {},
			onclose: () => {},
		},
		newMessage: "", //内容
		nowIP: socketNowIP,
		isGetRelationshiplist: false, //是否重新请求联系人
		confirmed: true, //是否弹窗 一次只能弹一个
		HeartBeatItem: 0, //心跳检测标识
		onlineUsers: [], // 用户在线列表
		userCount: 1, //用户在线数
	}),
	mutations: {
		setOnSend(state, data) {
			state.socket.send(JSON.stringify(data))
		},
		setIsGetRelationshiplist(state, data) {
			state.isGetRelationshiplist = data
		},
		setHeartBeatItem(state, data) {
			clearInterval(state.HeartBeatItem)
			state.HeartBeatItem = setInterval(() => {
				if(state.socket.readyState==3){
					clearInterval(state.HeartBeatItem)
				}else if(state.socket.readyState==1){
					state.socket.send(JSON.stringify({
						type: 10,
						data: "30sHeartBeat"
					}));
				}
			}, 30000)
		},
		setNewMessage(state, data) {
			state.newMessage = Object.assign({}, data);
		},
		//设置用户数量
		setUserCount(state,data){
			state.userCount = data || 1
		},
		//设置在线用户列表
		setOnlineUsers(state, data) {
			state.onlineUsers = data
		},
		OnlineUsersPush(state, data) {
			state.onlineUsers.push(data)
		},
		//退出
		socketLogOut(state, data) {
			state.socket.close()
		}
		
	},
	actions: {
		socketInit(context, data) {
			if (typeof WebSocket === "undefined") {
				alert("您的浏览器不支持socket");
			} else {
				let {Id,username}=data[0]
				// let remarks=data[1] || "login"
				
				// let path = socketNowIP +remarks+"/"+ Id + "/" + username + "/" + getToken(); // 请求路径 V1
				let path = socketNowIP + Id + "/" + username; // 请求路径
				let socket = new WebSocket(path);
				socket.onopen = open.bind(this);
				socket.onerror = error.bind(this);
				socket.onmessage = getMessage.bind(this);
				socket.onclose = close.bind(this);
				context.state.socket = socket;
				context.commit("setHeartBeatItem")
				
			}
		},
		

	}
}

export default socketService



function open() {
	console.log("socket连接成功");
	let sendobj={
		type:1024,
		message:"push token",
		token:getToken()
	}
	this.commit("setOnSend",sendobj)
}

function error() {
	console.log("连接错误");
}
//接受信息
function getMessage(event) {
	let _this = this;
	return new Promise((resolve, reject) => {
		// 利用promise 返回出去结果
		if (typeof event.data === 'string') {
			var message = JSON.parse(event.data);
			if (confirmCconfig.isTure && message.type === -1 && message.code === 401) {
				confirmCconfig.isTure = false;
				MessageBox.confirm('登录失效，可以取消继续留在该页面,或者重新登录', '提示', {
					confirmButtonText: '重新登录',
					cancelButtonText: '取消',
					type: 'warning'
				}).then((data) => {
					confirmCconfig.isTure = true;
					router.push('/login')
					reject("token失效");
					_this.commit("socketLogOut")
				}).catch(err => {
					confirmCconfig.isTure = true;
					_this.commit("socketLogOut")
					reject("token失效");
				})
				return;
			}
			_this.commit("setNewMessage",message)
			resolve(message);
		};
	});

}
//发送信息
function send(data) {
	if(socketService.state.socket.readyState==1){
		this.commit("setOnSend",data)
	}
}

function close() {
	console.log("socket已经关闭");
}